// pages/member-applyHeader/member-applyHeader.js
import api from '../../utils/api.js'
let app = getApp();
import { config } from '../../utils/config'
import {
    HTTP
} from "../../utils/http.js";
import WxValidate from "../../utils/WxValidate.js";
import WeCropper from "../../utils/we-cropper/we-cropper.min.js";
const device = wx.getSystemInfoSync() // 获取设备信息
const width = device.windowWidth // 示例为一个与屏幕等宽的正方形裁剪框
const height = width

let http = new HTTP();
Page({
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        cropperOpt: {
            id: 'cropper', // 用于手势操作的canvas组件标识符
            targetId: 'targetCropper', // 用于用于生成截图的canvas组件标识符
            pixelRatio: device.pixelRatio, // 传入设备像素比
            width, // 画布宽度
            height, // 画布高度
            scale: 3, // 最大缩放倍数
            zoom: 8, // 缩放系数 // 裁剪框x轴起点  // 裁剪框y轴期起点
            cut: {
                x: (width - 200) / 2,
                y: (width - 200) / 2,
                width: 200, // 裁剪框宽度
                height: 200 // 裁剪框高度
            }
        },
        showCropper: false, // 头像 裁剪层
        showModel: false, // 模态窗口
        showDetail: false, //选择社区 地址
        arrayAdress: [], //社区地址
        avatar: '',
        onLineimages: [],
        headerData: {
            name: "", //团队名称
            manifesto: "", //团队宣言
            user_name: "", //团长姓名
            community_name: "", //社区区名
            community_address: "", //社区区地址
            phone_number: "", //电话号码
            city_id: wx.getStorageSync('city_id'), //城市ID
            image: null, //团队头像
            client_id: wx.getStorageSync('user_id') //用户id
        },
        communityName: [], //获取 接口 返回的 小区名称 列表
        communityNameNone: false, // 当接口返回201，没有小区列表时
        index: null,
        indexN: null,
        imgUrl: config.imgUrl,
        handEnterName: '', //手动输入的 小区名
    },
    initValidate() {
        let rules = {
            user_name: {
                required: true,
                maxlength: 10
            },
            name: {
                required: true,
                maxlength: 12
            },
            manifesto: {
                required: true,
                maxlength: 18
            },

            community_name: {
                required: true,
                maxlength: 18
            },
            community_address: {
                required: true,
                maxlength: 18,
                minlength: 0
            },
            phone_number: {
                required: true,
                tel: true
            },
        }

        let message = {
                user_name: {
                    required: "请输入团长姓名",
                    maxlength: '团长姓名不能超过10个字'
                },
                name: {
                    required: '请输入团队名称',
                    maxlength: '团队名称不能超过12个字'
                },
                manifesto: {
                    required: '请输入团队宣言',
                    maxlength: "团队宣言不能超过18个字"
                },

                community_name: {
                    required: "请输入社区名称",
                    maxlength: "社区名称不能超过18个字",
                },
                community_address: {
                    required: "请输入社区地址",
                    maxlength: "社区地址不能超过18个字",
                },
                phone_number: {
                    required: "请输入手机号码",
                    tel: "请输入11位的手机号码",
                },
            }
            //实例化当前的验证规则和提示消息
        this.WxValidate = new WxValidate(rules, message);
    },
    //填写团队名称
    bindInputName: function(e) {
        let value = e.detail.value;
        let name = "headerData.name";
        this.setData({
            [name]: value
        });
    },
    //填写团队宣言
    bindInputManifesto(e) {
        let value = e.detail.value;
        let manifesto = "headerData.manifesto";
        this.setData({
            [manifesto]: value
        });
    },
    //填写团长姓名
    bindInputUser_name(e) {
        let value = e.detail.value;
        let user_name = "headerData.user_name";
        this.setData({
            [user_name]: value
        });
    },
    //填写小区名
    bindInputCommunity_name(e) {
        let handEnterName = e.detail.value;
        let community_name = "headerData.community_name";
        this.setData({
            handEnterName,
            [community_name]: handEnterName,
        });
    },
    //填写完成时，，点击完成按钮时触发，
    sendTextMsg(e) {
        console.log('eeeeeeeeee', e)
        let replyContent = e.detail.value;

        this.setData({
            sendTextMsg: true, //点击完成按钮时触发
            communityNameNone: false
        })

    },
    //滚动选择小区地址
    bindPickerChange: function(e) {
        // console.log("picker", e);
        let index = e.detail.value;
        let community_name = "headerData.community_name";
        console.log('index', index);
        this.setData({
            indexN: 0,
            handEnterName: '',
            [community_name]: ''
        })
        let allAddressInfo = this.data.allAddressInfo;
        let arrayAdress = this.data.arrayAdress;
        let community_address = "headerData.community_address";
        this.setData({
            index: e.detail.value,
            [community_address]: arrayAdress[index],
            lon: allAddressInfo[index].lon,
            lat: allAddressInfo[index].lat
        });
        let lan = allAddressInfo[index].lon;
        let lat = allAddressInfo[index].lat;


        this.getUserUptowns(lan, lat)
    },
    //选择小区名称 或 新填写小区名称
    pickerCommunityName: function(e) {
        let communityName = this.data.communityName;

        console.log('eeeeeeeee', e)
        let indexN = e.detail.value;
        console.log('indexN', indexN)

        let len = communityName.length;
        console.log('len', len)
        let community_name = "headerData.community_name";
        this.setData({
            sendTextMsg: false, //点击完成按钮时触发
        })

        if (Number(indexN) + 1 == len) {
            console.log(1111111111)
            this.setData({
                communityNameNone: true,
                indexN,
                [community_name]: '' // 选择 手动 输入小区名称时，清空
            })
        } else {
            console.log(222222222222222)
            this.setData({
                communityNameNone: false,
                indexN,
                [community_name]: communityName[indexN]
            })
        }

    },
    // 必须先选择小区地址
    firstGetAddress() {
        let communityName = this.data.communityName;
        if (communityName.length == 0) {
            console.log(333333)
            wx.showToast({
                title: '请先选择小区地址',
                icon: 'none',
                duration: 1500,
                mask: true
            })

            return false;
        }
    },
    //填写电话号码
    bindInputPhone_number(e) {
        let value = e.detail.value;
        let phone_number = "headerData.phone_number";
        this.setData({
            [phone_number]: value
        });
    },
    //本地上传头像
    chooseImage(e) {
        this.setData({
            showCropper: true
        })
        let that = this;
        let images = that.data.images;
        // 选择图片
        // wx.chooseImage({
        //   count: 1,
        //   sizeType: ["compressed"],
        //   sourceType: ["album", "camera"],
        //   success: function(res) {
        //     let tempFilePaths = res.tempFilePaths;
        //     that.setData({
        //       avatar: tempFilePaths
        //     });
        //   }
        // });
    },
    //取消上传
    cancelUp() {
        this.setData({
            showCropper: false
        })
    },
    formSubmit: function(e) {
        // console.log('form发生了submit事件，携带数据为：', e.detail.value)

        // let headerData = e.detail.value;
        // let arrayAdress = this.data.arrayAdress;    //社区地址
        // headerData.community_address = arrayAdress[headerData.community_address]
        let avatar = this.data.avatar; //团队头像
        let headerData = this.data.headerData;
        let communityNameNone = this.data.communityNameNone; //true,即新增

        if (communityNameNone) {
            let user_id = wx.getStorageSync('user_id');
            let lon = this.data.lon;
            let lat = this.data.lat;
            let community_name = this.data.headerData.community_name;

            console.log('lon', lon)
            console.log('lat', lat)
            let city_id = wx.getStorageSync('city_id');
            this.addNationwideUptown(user_id, lon, lat, community_name, city_id)
        }

        // console.log('hhhhhhhhh', headerData);
        //如果用户本地上传了头像
        if (avatar.length == 0) {
            wx.showToast({
                title: `您还没有上传团队头像`,
                icon: 'none',
                mas: true
            })
            return false;
        } else {

        }
        // 校验表单
        if (!this.WxValidate.checkForm(headerData)) {
            const error = this.WxValidate.errorList[0];
            wx.showToast({
                title: `${error.msg} `,
                icon: 'none',
                mask: true
            })
            return false;
        }
        console.log('000000000000', avatar)
        wx.showLoading({
            title: '上传头像中',
        })
        wx.uploadFile({
            url: "https://xiangtws.com/public/index.php/api/Status/uploadImages",
            filePath: avatar,
            name: 'images[]', //与后台 命名的数组对应
            success: (res) => {
                if (res.statusCode == 200) {
                    wx.hideLoading();
                    let onLineimages = res.data; //线上 图片 路径
                    console.log('onLineimages', onLineimages)
                    let image = "headerData.image";
                    this.setData({
                        [image]: onLineimages,
                    });
                    this.userAddOrganization(headerData)

                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showModal({
                    title: '错误提示',
                    content: '上传图片失败',
                    showCancel: false,
                    success: function(res) {}
                })
            }
        });
    },
    //申请 团长
    userAddOrganization(headerData) {
        console.log('============headerData==============', headerData)
        http.request({
            url: api.userAddOrganiZation,
            data: headerData,
            success: (res) => {
                console.log('11111111111', res);
                if (res.error_code == 40001) {
                    let msg = res.msg;
                    console.log(msg);
                    wx.showToast({
                        title: "您已经申请过了",
                        icon: 'none',
                        mask: true,
                        duration: 1500,
                        success: () => {
                            setTimeout(() => {
                                wx.navigateBack()
                            }, 2000)
                        }
                    })
                } else if (res.code == 200) {
                    wx.showToast({
                        title: '申请创建社区团成功',
                        icon: 'success',
                        mask: true,
                        duration: 1500,
                        success: () => {
                            setTimeout(() => {
                                wx.navigateBack()
                            }, 2000)
                        }
                    })
                }
            }
        });
    },
    //存储用户的小区名全国加经纬度, 当用户手动输入小区名称即新增小区名称调用
    addNationwideUptown(user_id, lon, lat, community_name, city_id) {
        http.request({
            url: api.addNationwideUptown,
            data: {
                id: user_id,
                lon: lon,
                lat: lat,
                community_name: community_name,
                city_id: city_id
            },
            success: (res) => {
                console.log('存储用户的小区名', res);
            }
        });
    },
    onLoad: function(options) {
        let city = wx.getStorageSync('city');
        let city_id = wx.getStorageSync('city_id');
        let user_id = wx.getStorageSync('user_id');
        this.data.headerData.client_id = user_id;
        this.data.headerData.city_id = city_id;
        if (city_id && user_id) {
            let h1 = "headerData.city_id";
            let h2 = "headerData.client_id";
            this.setData({
                [h1]: city_id,
                [h2]: user_id
            });
        }

        const {
            cropperOpt
        } = this.data
        this.mycropper = new WeCropper(cropperOpt)
            .on('ready', (ctx) => {
                console.log(`wecropper is ready for work!`)
            })
            .on('beforeImageLoad', (ctx) => {
                wx.showToast({
                    title: '上传中',
                    icon: 'loading',
                    duration: 15000,
                    mask: true
                })
            })
            .on('imageLoad', (ctx) => {
                wx.hideToast()
            })
        this.initValidate(); // 表单验证
        this.getUserAllAddress(user_id);
    },
    touchStart(e) {
        this.mycropper.touchStart(e)
    },
    touchMove(e) {
        this.mycropper.touchMove(e)
    },
    touchEnd(e) {
        this.mycropper.touchEnd(e)
    },
    //点击上传图片按钮后获取图片地址，并通过pushOrign方法载入图片
    uploadTap() {
        const self = this

        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success(res) {
                const src = res.tempFilePaths[0]

                self.mycropper.pushOrign(src)
            }
        })
    },
    //点击生成图片按钮，导出图片
    getCropperImage() {
        this.mycropper.getCropperImage((tempFilePath) => {
            // tempFilePath 为裁剪后的图片临时路径
            if (tempFilePath) {
                // wx.previewImage({
                //   current: '',
                //   urls: [tempFilePath]
                // })
                this.setData({
                    avatar: tempFilePath,
                    showCropper: false
                });

            } else {
                console.log('获取图片地址失败，请稍后重试')
            }
        })
    },
    //拿到用户 所有已存在的地址-社区地址
    getUserAllAddress(user_id) {
        let self = this;
        http.request({
            url: api.getUserAllAddress,
            data: {
                id: user_id
            },
            success: (res) => {
                if (res.code == 200) {

                    let data = res.data;
                    let adress = [];
                    let allAddressInfo = [];
                    data.forEach((ele) => {
                        adress.push(ele.address);
                        allAddressInfo.push(ele)
                    })
                    self.setData({
                        arrayAdress: adress,
                        allAddressInfo: allAddressInfo
                    })
                }
            }
        });
    },
    //根据经纬度以及城市ID拿到用户附近的小区列表名称, 用户也可自主新加 小区名称
    getUserUptowns(lon, lat) {
        let city_id = wx.getStorageSync('city_id')
        console.log('city_id', city_id)
        http.request({
            url: api.getUserUptowns,
            data: {
                lon,
                lat,
                city_id
            },
            success: (res) => {
                console.log('111111111111', res)
                if (res.code == 200) {
                    let communityName = res.data; // x
                    let arr = []
                    for (let i in communityName) {
                        arr.push(communityName[i]);
                    }
                    console.log(arr);
                    arr.push('请手动输入小区名称')
                    this.setData({
                        communityName: arr,
                        communityNameNone: false
                    })

                } else if (res.code == 201) {
                    console.log('您的附近还没有小区列表，请您添加新的')
                    let communityName = []
                    communityName.push('请手动输入小区名称')
                    this.setData({
                        communityName,
                        communityNameNone: false
                    })
                }
            }
        });
    },
    onUnload: function() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {},


});